console.log("hello index .js")
var chat_content = $("#chat-content")



var color_class = [
    '#2196F3', '#32c787', '#00BCD4', '#ff5652',
    '#ffc107', '#ff85af', '#FF9800', '#39bbb0'
];
//按钮
var sendbtn = $("#send")
var connectbtn = $("#connect")
var leavebtn = $("#leave")

var stompClient = null;
var username = null;

leavebtn.click(function () {
    namevalue = $("#name").val()
    // console.log("hello word" )
    console.log(namevalue)
})


connectbtn.click(connect)

function connect(event) {
    namevalue = $("#name").val()
    username = namevalue
    console.log("start server")
    if(namevalue){
        //创建套接字
        var socket = new SockJS("/ws")
        console.log(socket)
        stompClient = Stomp.over(socket)
        // alert("创建套接字")
        // stompClient.connect({},onConnected,onError)
        stompClient.connect({},function (data) {
            stompClient.subscribe("/user/1/sendMessage",function (body) {
                console.log(body)
            })
        },function (data) {
            console.log(连接错误)
        })
    }
    event.preventDefault()
}

function onError(error) {

    var connection_tip = $('span',{
        text:"can't connect",
        style:'layui-badge'
    })
    chat_content.append(connection_tip)
}

function sendMessage(event) {
    message_content = $("#message_content").text()
    //如果信息内容不为空  而且  邮箱也可以就
    if(stompClient && message_content){
        var chatMessage = {
            sender : username,
            content: message_content,
            type: "CHAT"
        }
        stompClient.send("/app/chat.sendMessage",{},JSON.stringify(message_content))
        $("#message_content").text("")
    }
    event.preventDefault();


}

function onConnected() {
    // Subscribe to the Public Topic
    stompClient.subscribe('/topic/public', onMessageReceived);

    // Tell your username to the server
    stompClient.send("/app/chat.addUser",
        {},
        JSON.stringify({sender: username, type: 'JOIN'})
    )
}
//收到消息的处理


function onMessageReceived(payload){
    var message = JSON.parse(payload)
    //创建聊天对象
    var messagespan = $('<span>',{
        text:"baidu",
        class:"layui-badge"
    });
    if(message.type === 'JOIN'){
        messagespan.text(message.sender + 'Joined')

    }
    else if(message.type === 'LEAVE'){
        messagespan.text(message.sender + "Leave")
    }
    else {
        messagespan.text(message.sender + ":" + message.content)
    }

    chat_content.append(messagespan)
    chat_content.scrollTop = chat_content._scrollHeight;
}










$("#test1").click(function () {
    var span = $('<span>',{
        text:"",
        class:"layui-badge"
    });
    //取得颜色 设置内容
    var number = Math.random()*8
    console.log(parseInt(number))
    span.css("background",color_class[parseInt(number)])
    // span.text("sssss")
    $("#chat-content").append(span,'</br>')
})